import 'package:flutter/material.dart';
import '../../widgets/NavigationView.dart';
import '../../widgets/news_card.dart';
import '../../models/news_model.dart';
import '../../routes/Router.dart';
import '../../services/umeng_analytics.dart';

class CategoryPage extends StatefulWidget {
  final String categoryId;
  final String categoryName;

  const CategoryPage({
    super.key,
    required this.categoryId,
    required this.categoryName,
  });

  @override
  State<CategoryPage> createState() => _CategoryPageState();
}

class _CategoryPageState extends State<CategoryPage> {
  late List<NewsModel> _newsList;

  @override
  void initState() {
    super.initState();
    _loadNews();
    UmengAnalytics.onPageStart('CategoryPage');
  }

  @override
  void dispose() {
    UmengAnalytics.onPageEnd('CategoryPage');
    super.dispose();
  }

  void _loadNews() {
    // 模拟分类新闻数据
    _newsList = List.generate(
      8,
      (index) => NewsModel(
        id: '${widget.categoryId}_$index',
        title:
            '${widget.categoryName}新闻 $index - 这是一条${widget.categoryName}相关的资讯',
        content: '${widget.categoryName}新闻内容 $index - 这里是详细的新闻内容。',
        imageUrl: index % 2 == 0
            ? ''
            : 'https://picsum.photos/400/300?random=${100 + index}',
        category: widget.categoryName,
        publishTime: DateTime.now().subtract(Duration(hours: index)),
        author: ['记者A', '记者B', '记者C'][index % 3],
      ),
    );
  }

  void _onNewsTap(NewsModel news) {
    UmengAnalytics.onEvent(
      'view_news',
      properties: {'news_id': news.id, 'category': news.category},
    );

    Navigator.pushNamed(
      context,
      AppRoutes.newsDetail,
      arguments: {'id': news.id, 'title': news.title},
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: NavigationView(title: widget.categoryName),
      body: ListView.builder(
        itemCount: _newsList.length,
        itemBuilder: (context, index) {
          return NewsCard(
            news: _newsList[index],
            onTap: () => _onNewsTap(_newsList[index]),
          );
        },
      ),
    );
  }
}
